import 'dart:async';
import 'package:flutter/material.dart';
import 'package:delivery_application/view/home/success_deliver.dart';
import 'dart:math' as math;

class DeliveryMapView extends StatefulWidget {
  final double destinationLat;
  final double destinationLng;
  
  const DeliveryMapView({
    super.key, 
    required this.destinationLat, 
    required this.destinationLng
  });

  @override
  State<DeliveryMapView> createState() => _DeliveryMapViewState();
}

class _DeliveryMapViewState extends State<DeliveryMapView> with SingleTickerProviderStateMixin {
  // 动画相关
  late AnimationController _animationController;
  late Animation<double> _animation;
  
  // 配送时间 (毫秒)
  final int _deliveryTime = 30000; // 30秒（您可以根据需要调整）
  
  // 配送起点和终点（仅展示用）
  late String _startAddress;
  late String _destinationAddress;
  
  @override
  void initState() {
    super.initState();
    
    // 初始化位置信息
    _startAddress = "配送中心 (39.9042, 116.4074)";
    _destinationAddress = "收货地址 (${widget.destinationLat.toStringAsFixed(4)}, ${widget.destinationLng.toStringAsFixed(4)})";
    
    // 设置动画
    _animationController = AnimationController(
      duration: Duration(milliseconds: _deliveryTime),
      vsync: this,
    );
    
    _animation = Tween<double>(begin: 0.0, end: 1.0).animate(_animationController)
      ..addListener(() {
        setState(() {});
      })
      ..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          // 动画完成后，延迟一秒跳转到成功页面
          Future.delayed(Duration(seconds: 1), () {
            if (mounted) {
              Navigator.pushReplacement(
                context,
                MaterialPageRoute(
                  builder: (context) => const SuccessDiliver(),
                ),
              );
            }
          });
        }
      });
    
    // 延迟一秒开始动画
    Future.delayed(Duration(seconds: 1), () {
      _animationController.forward();
    });
  }
  
  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }
  
  @override
  Widget build(BuildContext context) {
    // 获取屏幕尺寸
    final Size size = MediaQuery.of(context).size;
    
    return Scaffold(
      backgroundColor: Color(0xff00AEEE),
      appBar: AppBar(
        title: Text("订单配送中", style: TextStyle(color: Colors.white)),
        backgroundColor: Color(0xff00AEEE),
        iconTheme: IconThemeData(color: Colors.white),
      ),
      body: Column(
        children: [
          // 模拟地图区域
          Expanded(
            child: Container(
              margin: EdgeInsets.all(15),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(10),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black12,
                    blurRadius: 8,
                    offset: Offset(0, 2),
                  ),
                ],
              ),
              child: Stack(
                children: [
                  // 地图背景
                  Positioned.fill(
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(10),
                      child: Stack(
                        children: [
                          // 模拟地图网格
                          CustomPaint(
                            size: Size.infinite,
                            painter: GridPainter(),
                          ),
                          // 模拟地图标记
                          Positioned.fill(
                            child: Center(
                              child: Icon(
                                Icons.map,
                                size: 120,
                                color: Color(0xff00AEEE).withOpacity(0.07),
                              ),
                            ),
                          ),
                          // 模拟道路 - 移除水平道路以支持斜线路径
                        ],
                      ),
                    ),
                  ),
                  
                  // 路线
                  CustomPaint(
                    size: Size(double.infinity, double.infinity),
                    painter: DeliveryPathPainter(
                      progress: _animation.value,
                    ),
                  ),
                  
                  // 起点标记
                  Positioned(
                    top: 50,
                    left: 30,
                    child: Column(
                      children: [
                        Icon(
                          Icons.home_work,
                          color: Colors.blue,
                          size: 30,
                        ),
                        SizedBox(height: 5),
                        Container(
                          padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                          decoration: BoxDecoration(
                            color: Colors.blue.withOpacity(0.2),
                            borderRadius: BorderRadius.circular(10),
                          ),
                          child: Text(
                            "起点",
                            style: TextStyle(
                              fontSize: 12,
                              color: Colors.blue,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  
                  // 终点标记
                  Positioned(
                    bottom: 50,
                    right: 30,
                    child: Column(
                      children: [
                        Icon(
                          Icons.location_pin,
                          color: Colors.red,
                          size: 30,
                        ),
                        SizedBox(height: 5),
                        Container(
                          padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                          decoration: BoxDecoration(
                            color: Colors.red.withOpacity(0.2),
                            borderRadius: BorderRadius.circular(10),
                          ),
                          child: Text(
                            "终点",
                            style: TextStyle(
                              fontSize: 12,
                              color: Colors.red,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
          
          // 地址信息
          Container(
            margin: EdgeInsets.symmetric(horizontal: 15),
            padding: EdgeInsets.all(15),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10),
            ),
            child: Column(
              children: [
                Row(
                  children: [
                    Icon(Icons.home_work, color: Colors.blue, size: 20),
                    SizedBox(width: 10),
                    Expanded(
                      child: Text(
                        _startAddress,
                        style: TextStyle(fontSize: 14),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 5),
                Divider(),
                SizedBox(height: 5),
                Row(
                  children: [
                    Icon(Icons.location_pin, color: Colors.red, size: 20),
                    SizedBox(width: 10),
                    Expanded(
                      child: Text(
                        _destinationAddress,
                        style: TextStyle(fontSize: 14),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          
          // 配送进度
          Container(
            margin: EdgeInsets.all(15),
            padding: EdgeInsets.all(15),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10),
              boxShadow: [
                BoxShadow(
                  color: Colors.black26,
                  blurRadius: 5,
                  offset: Offset(0, 2),
                ),
              ],
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  "配送进度",
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                SizedBox(height: 10),
                LinearProgressIndicator(
                  value: _animation.value,
                  backgroundColor: Colors.grey[300],
                  valueColor: AlwaysStoppedAnimation<Color>(Colors.green),
                  minHeight: 10,
                  borderRadius: BorderRadius.circular(5),
                ),
                SizedBox(height: 10),
                Text(
                  "预计剩余时间: ${((_deliveryTime * (1 - _animation.value)) / 1000).round()} 秒",
                  style: TextStyle(fontSize: 14),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

// 自定义绘制配送路径
class DeliveryPathPainter extends CustomPainter {
  final double progress;
  
  DeliveryPathPainter({required this.progress});
  
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.blue
      ..style = PaintingStyle.stroke
      ..strokeWidth = 3.0;
    
    // 起点和终点的位置（改为斜线）
    final startX = 30.0;
    final startY = 50.0;
    final endX = size.width - 30;
    final endY = size.height - 50;
    
    // 绘制道路中心的虚线 - 对于斜线，我们使用Path来绘制虚线
    final dashPaint = Paint()
      ..color = Colors.yellow
      ..style = PaintingStyle.stroke
      ..strokeWidth = 2.0;
    
    final dashWidth = 10.0;
    final dashSpace = 10.0;
    
    // 计算路径总长度
    double pathLength = _calculateDistance(startX, startY, endX, endY);
    double distance = 0.0;
    
    while (distance < pathLength) {
      // 计算虚线的开始和结束点
      double ratio1 = distance / pathLength;
      double ratio2 = (distance + dashWidth) / pathLength;
      ratio2 = ratio2 > 1.0 ? 1.0 : ratio2;
      
      double x1 = startX + (endX - startX) * ratio1;
      double y1 = startY + (endY - startY) * ratio1;
      double x2 = startX + (endX - startX) * ratio2;
      double y2 = startY + (endY - startY) * ratio2;
      
      // 绘制虚线段
      canvas.drawLine(
        Offset(x1, y1),
        Offset(x2, y2),
        dashPaint,
      );
      
      distance += dashWidth + dashSpace;
    }
    
    // 绘制完整路径（灰色）
    final fullPath = Path();
    fullPath.moveTo(startX, startY);
    fullPath.lineTo(endX, endY);
    
    final grayPaint = Paint()
      ..color = Colors.grey.withOpacity(0.3)
      ..style = PaintingStyle.stroke
      ..strokeWidth = 3.0;
    
    canvas.drawPath(fullPath, grayPaint);
    
    // 绘制当前进度路径（蓝色）
    final currentPath = Path();
    currentPath.moveTo(startX, startY);
    
    final endXProgress = startX + (endX - startX) * progress;
    final endYProgress = startY + (endY - startY) * progress;
    currentPath.lineTo(endXProgress, endYProgress);
    
    canvas.drawPath(currentPath, paint);
    
    // 绘制路径上的点
    final pointPaint = Paint()
      ..color = Colors.blue
      ..style = PaintingStyle.fill;
    
    canvas.drawCircle(Offset(startX, startY), 5, pointPaint);
    
    final currentPointPaint = Paint()
      ..color = Colors.green
      ..style = PaintingStyle.fill;
    
    canvas.drawCircle(Offset(endXProgress, endYProgress), 5, currentPointPaint);
    
    if (progress == 1.0) {
      final endPointPaint = Paint()
        ..color = Colors.red
        ..style = PaintingStyle.fill;
      
      canvas.drawCircle(Offset(endX, endY), 5, endPointPaint);
    }
  }
  
  // 辅助方法：计算两点之间的距离
  double _calculateDistance(double x1, double y1, double x2, double y2) {
    return math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
  }
  
  @override
  bool shouldRepaint(DeliveryPathPainter oldDelegate) {
    return oldDelegate.progress != progress;
  }
}

// 添加网格绘制类
class GridPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.grey.withOpacity(0.1)
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1.0;
    
    final gridSize = 20.0;
    
    // 绘制水平线
    for (double y = 0; y < size.height; y += gridSize) {
      canvas.drawLine(Offset(0, y), Offset(size.width, y), paint);
    }
    
    // 绘制垂直线
    for (double x = 0; x < size.width; x += gridSize) {
      canvas.drawLine(Offset(x, 0), Offset(x, size.height), paint);
    }
  }
  
  @override
  bool shouldRepaint(GridPainter oldDelegate) => false;
} 